import React, { memo, useEffect, useRef, useState } from 'react';
import {
  Form,
  Row,
  Col,
  Input,
  Button,
  DatePicker,
  Select,
  Textarea,
  Upload,
  MessagePlugin,
  Checkbox,
  Space,
} from 'tdesign-react';
import classnames from 'classnames';
import { SubmitContext, FormInstanceFunctions } from 'tdesign-react/es/form/type';
import CommonStyle from 'styles/common.module.less';
import Style from './index.module.less';
import { addCourse } from 'api/course/course';
import { getGoodsTypeList } from 'api/goodsType';
import { addGoods } from 'api/goods';

const { FormItem } = Form;
const { Option } = Select;
const INITIAL_DATA = {
  name: '',
  type: '',
  payment: '',
  partyA: '',
  partyB: '',
  signDate: '',
  effectiveDate: '',
  endDate: '',
  remark: '',
  notary: '',
  file: [],
};

interface tmpGoodsType {
  id: string;
  typeName: string;
}

export default memo(() => {
  const formRef = useRef<FormInstanceFunctions>();

  const [goodsType, setGoodsType] = useState<tmpGoodsType[]>([]);
  useEffect(() => {
    getGoodsTypeList({}).then((res) => {
      const data = res.data.map((v) => {
        const tmp: tmpGoodsType = { id: v.id, typeName: v.typeName };
        return tmp;
      });
      setGoodsType(data);
    });
  }, []);

  const onSubmit = async (e: SubmitContext) => {
    if (e.validateResult === true) {
      const addValue = formRef.current?.getFieldsValue?.(true) as any;

      addValue.picture = addValue.picture.length !== 0 ? addValue.picture[0].response.name : '';
      const res = await addGoods(addValue);
      if (res.data) {
        MessagePlugin.success(`添加${res.msg}`);
      } else {
        MessagePlugin.error(`添加${res.msg}`);
      }
      formRef?.current?.reset();
    }
  };

  const handleFail = ({ file }: { file: any }) => {
    console.error(`文件 ${file.name} 上传失败`);
  };

  return (
    <div className={classnames(CommonStyle.pageWithColor)}>
      <div className={Style.formContainer}>
        <Form ref={formRef} onSubmit={onSubmit} labelWidth={100} labelAlign='top'>
          <div className={Style.titleBox}>
            <div className={Style.titleText}>商品信息</div>
          </div>
          <Row gutter={[32, 24]}>
            <Col span={6}>
              <FormItem
                label='商品名称'
                name='name'
                rules={[{ required: true, message: '商品名称必填', type: 'error' }]}
              >
                <Input placeholder='请输入商品名称' />
              </FormItem>
            </Col>

            <Col span={6}>
              <FormItem
                label='商品类型'
                name='typeKey'
                rules={[{ required: true, message: '商品类型必填', type: 'error' }]}
              >
                <Select placeholder='请选择商品类型'>
                  {goodsType.map((v, idx) => (
                    <Option key={idx} label={v.typeName} value={v.id} />
                  ))}
                </Select>
              </FormItem>
            </Col>

            <Col span={6}>
              <FormItem label='商品定价' name='price' rules={[{ required: true }]}>
                <Input placeholder='请输入商品定价' style={{ width: 160 }} />
              </FormItem>
            </Col>

            <Col span={3}>
              <FormItem label='商品数量' name='account' rules={[{ required: true }]}>
                <Input placeholder='请输入商品数量' style={{ width: 160 }} />
              </FormItem>
            </Col>
          </Row>

          <div className={Style.titleBox}>
            <div className={Style.titleText}></div>
          </div>

          <FormItem label='商品描述' name='description' initialData={INITIAL_DATA.remark}>
            <Textarea placeholder='请输入商品描述' />
          </FormItem>

          <FormItem label='图片' name='picture'>
            <Upload
              action='http://127.0.0.1:5000/upload/avatar'
              theme='image'
              tips='请选择单张图片文件上传'
              accept='image/*'
            ></Upload>
          </FormItem>

          <FormItem>
            <Button type='submit' theme='primary'>
              发布
            </Button>
            <Button type='reset' style={{ marginLeft: 12 }}>
              重置
            </Button>
          </FormItem>
        </Form>
      </div>
    </div>
  );
});
